package com.example.source_share.service.impl.user.account;

import com.example.source_share.pojo.User;
import com.example.source_share.service.impl.utils.JwtUtil;
import com.example.source_share.service.impl.utils.UserDetailsImpl;
import com.example.source_share.service.user.account.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    //这里点实现方法就能快速导入
    @Override
    public Map<String, String> getToken(String username, String password) {
        //封装用户名密码
        UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(username,password);
        //验证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果登录失败会自动处理，没报异常说明登录成功
        UserDetailsImpl loginUser=(UserDetailsImpl)  authenticate.getPrincipal(); //取出用户
        User user=loginUser.getUser();
        //将userid封装成jwt Token
        String jwt= JwtUtil.createJWT(user.getUserid().toString());
        Map<String,String > map =new HashMap<>();
        //发送
        System.out.println("用户登入："+username);
        map.put("purview",user.getPurview());
        map.put("message","Success!");
        map.put("token",jwt);
        return map;
    }
}
